package com.eight.cloud.openfeign.config;

import com.eight.cloud.core.global.result.Result;
import feign.FeignException;
import feign.Response;
import feign.codec.Decoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;

import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @ClassName: FeignResponseDecoder
 * @Author: TXC
 * @Date: 2024-10-13 23:00
 **/
public class FeignResponseDecoder implements Decoder {

    private final SpringDecoder springDecoder;

    public FeignResponseDecoder(SpringDecoder springDecoder) {
        this.springDecoder = springDecoder;
    }

    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException {
        Method method = response.request().requestTemplate().methodMetadata().method();
        //如果Feign接口的返回值不是 Result{code:0,...} 结构类型，并且远程响应又是这个结构
        boolean notTheSame = method.getReturnType() != Result.class;
        if (notTheSame) {
            //构造一个这个结构类型
            Type newType =
                    new ParameterizedType() {
                        @Override
                        public Type[] getActualTypeArguments() {
                            return new Type[]{type};
                        }

                        @Override
                        public Type getRawType() {
                            return Result.class;
                        }

                        @Override
                        public Type getOwnerType() {
                            return null;
                        }
                    };
            Result<?> result = (Result<?>) springDecoder.decode(response, newType);
            // 只返回data
            return result.getData();
        }
        return springDecoder.decode(response, type);
    }
}
